'use strict';

const { Model } = require('sequelize');

module.exports = (sequelize, DataTypes) => {
  class CrmCustomer extends Model {
    static associate(models) {
      // 定义关联
      CrmCustomer.belongsTo(models.Contact, { foreignKey: 'contactId', as: 'contact' });
      CrmCustomer.belongsTo(models.User, { foreignKey: 'createdBy', as: 'Creator' });
    }
  }
  
  CrmCustomer.init({
    contactId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'contacts',
        key: 'id'
      }
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    phone: {
      type: DataTypes.STRING,
      allowNull: true
    },
    notes: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    status: {
      type: DataTypes.ENUM('lead', 'prospect', 'customer', 'inactive'),
      defaultValue: 'lead'
    },
    source: {
      type: DataTypes.STRING,
      allowNull: true
    },
    industry: {
      type: DataTypes.STRING,
      allowNull: true
    },
    product: {
      type: DataTypes.STRING,
      allowNull: true
    },
    quantity: {
      type: DataTypes.STRING,
      allowNull: true
    },
    location: {
      type: DataTypes.STRING,
      allowNull: true
    },
    createdBy: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'users',
        key: 'id'
      }
    },
    rating: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      validate: {
        min: 0,
        max: 5
      }
    },
    nextFollowUp: {
      type: DataTypes.DATE,
      allowNull: true
    },
    dealSize: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: true,
      defaultValue: 0
    },
    lastContactDate: {
      type: DataTypes.DATE,
      allowNull: true
    }
  }, {
    sequelize,
    modelName: 'CrmCustomer',
    tableName: 'crm_customers',
    timestamps: true
  });
  
  return CrmCustomer;
}; 